/**
 * Created by Ysssssss on 2021/5/17.
 */
import React, { useState, useEffect } from 'react'
import {Button, Input} from "antd";
import {telephoneValidation} from "@utils/regex";
import notify from "@utils/tip";
import {useDispatch} from "react-redux";
import { sendVerifyCode } from "@sagas/user";

const VerificationCode = props => {
    const { codeType, value, onChange, mobileNumber, staticContext, ...otherProps } = props
    const [ countdown, setCountdown ] = useState(0)
    const dispatch = useDispatch()
    let countdownTimout = null

    useEffect(() => {
        if (countdown > 0) {
            countdownTimout = setTimeout(() => {
                setCountdown(countdown - 1)
            }, 1000)
        } else {
            countdownTimout = null
        }
        return () => {
            if (countdownTimout) {
                clearTimeout(countdownTimout)
                countdownTimout = null
            }
        }
    }, [countdown])

    const handleInputChange = (e) => {
        onChange && onChange(e.target.value)
    }

    const sendVerificationCode = () => {
        if (!telephoneValidation.test(mobileNumber)) {
            notify('error', '手机号格式不正确')
            return ;
        }

        dispatch(sendVerifyCode({
            mobile: mobileNumber,
            code_type: codeType,
        }, () => {
            setCountdown(60)
        }))
    }

    return (
        <Input
            { ...otherProps }
            value={value}
            onChange={handleInputChange}
            placeholder="请输入验证码"
            suffix={(
                <Button
                    type="text"
                    className="clr-green"
                    disabled={countdown !== 0}
                    onClick={sendVerificationCode}
                >
                    {countdown === 0 ? '获取验证码' : `${countdown}s 后重新获取`}
                </Button>
            )}
        />
    )
}

export default VerificationCode